import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FindOperator, IsNull, Repository } from 'typeorm';
import { ResourceDto } from './dto/resource.dto';
import { ResourceEntity } from './entities/resource.entity';

@Injectable()
export class ResourceService {
  constructor(
    @InjectRepository(ResourceEntity)
    private readonly resourceRepository: Repository<ResourceEntity>,
  ) {}
  /**
   * @Author: laotongshu
   * @Date: 2022-10-10 18:16:45
   * @LastEditors: laotongshu
   * @Description: 查询资源列表
   * @param {Object} {}
   * @return {*}
   */
  getResource() {
    return this.resourceRepository.find();
  }

  /**
   * @Author: laotongshu
   * @Date: 2022-10-10 15:59:34
   * @LastEditors: laotongshu
   * @Description: 创建资源
   * @param {Object} {}
   * @return {*}
   */
  async createResource(resourceDto: ResourceDto): Promise<any> {
    return this.resourceRepository.save(resourceDto);
  }

  /**
   * @Author: laotongshu
   * @Date: 2022-10-11 14:21:30
   * @LastEditors: laotongshu
   * @Description:  查询权限关系列表, 可无限层级
   * @param {Object} {}
   * @return {*}
   */
  async roleList(parentId: string | FindOperator<any> = IsNull()) {
    const root_list = await this.resourceRepository.findBy({ parentId });
    console.log('2022-10-11 14:25:48', root_list);
    return Promise.all(
      root_list.map(async (item) => {
        return {
          ...item,
          children: await this.roleList(item.id),
        };
      }),
    );
  }
}
